import React, { useState } from 'react'
import { Card, Table, Button, Modal, Form, Input, Select, DatePicker, Space, Tag, message, Upload, Image } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined, EyeOutlined } from '@ant-design/icons'
import Layout from '../components/Layout/Layout'
import dayjs from 'dayjs'

const { Option } = Select
const { TextArea } = Input

export default function Assets() {
  const [assets, setAssets] = useState([
    {
      id: 1,
      name: '联想ThinkPad笔记本',
      category: 'IT设备',
      model: 'ThinkPad X1',
      serialNumber: 'TP001234',
      purchaseDate: '2023-06-15',
      purchasePrice: 8500,
      currentValue: 6800,
      status: 'in_use',
      location: 'A区办公室',
      assignedTo: '张三',
      warrantyExpiry: '2026-06-15',
      maintenanceDate: '2024-01-10',
      description: '办公用笔记本电脑',
      image: ''
    },
    {
      id: 2,
      name: '佳能打印机',
      category: '办公设备',
      model: 'Canon LBP6230dn',
      serialNumber: 'CN005678',
      purchaseDate: '2023-03-20',
      purchasePrice: 1200,
      currentValue: 900,
      status: 'available',
      location: 'B区打印室',
      assignedTo: '',
      warrantyExpiry: '2025-03-20',
      maintenanceDate: '2023-12-15',
      description: '激光打印机',
      image: ''
    }
  ])

  const [modalVisible, setModalVisible] = useState(false)
  const [editingRecord, setEditingRecord] = useState(null)
  const [loading, setLoading] = useState(false)
  const [form] = Form.useForm()

  const statusColors = {
    in_use: 'green',
    available: 'blue',
    maintenance: 'orange',
    retired: 'red',
    lost: 'purple'
  }

  const statusTexts = {
    in_use: '使用中',
    available: '可用',
    maintenance: '维护中',
    retired: '已报废',
    lost: '丢失'
  }

  const categoryOptions = [
    'IT设备',
    '办公设备',
    '家具',
    '车辆',
    '工具',
    '其他'
  ]

  const columns = [
    {
      title: '资产信息',
      key: 'asset',
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{record.name}</div>
          <div style={{ fontSize: 12, color: '#666' }}>
            {record.model} | {record.serialNumber}
          </div>
        </div>
      ),
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category) => <Tag>{category}</Tag>
    },
    {
      title: '购买信息',
      key: 'purchase',
      render: (_, record) => (
        <div>
          <div>购买日期: {record.purchaseDate}</div>
          <div style={{ fontSize: 12, color: '#666' }}>
            购买价格: ¥{record.purchasePrice}
          </div>
          <div style={{ fontSize: 12, color: '#666' }}>
            当前价值: ¥{record.currentValue}
          </div>
        </div>
      ),
    },
    {
      title: '状态',
      key: 'status',
      render: (_, record) => (
        <Tag color={statusColors[record.status]}>
          {statusTexts[record.status]}
        </Tag>
      ),
    },
    {
      title: '位置/使用人',
      key: 'location',
      render: (_, record) => (
        <div>
          <div>{record.location}</div>
          {record.assignedTo && (
            <div style={{ fontSize: 12, color: '#666' }}>
              使用人: {record.assignedTo}
            </div>
          )}
        </div>
      ),
    },
    {
      title: '保修到期',
      dataIndex: 'warrantyExpiry',
      key: 'warrantyExpiry',
      render: (date) => {
        const isExpiringSoon = dayjs(date).diff(dayjs(), 'days') < 30
        return (
          <span style={{ color: isExpiringSoon ? '#ff4d4f' : 'inherit' }}>
            {date}
          </span>
        )
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ]

  const handleAdd = () => {
    setEditingRecord(null)
    form.resetFields()
    setModalVisible(true)
  }

  const handleEdit = (record) => {
    setEditingRecord(record)
    form.setFieldsValue({
      ...record,
      purchaseDate: dayjs(record.purchaseDate),
      warrantyExpiry: dayjs(record.warrantyExpiry),
      maintenanceDate: dayjs(record.maintenanceDate)
    })
    setModalVisible(true)
  }

  const handleView = (record) => {
    Modal.info({
      title: '资产详情',
      width: 600,
      content: (
        <div style={{ marginTop: 16 }}>
          <div style={{ marginBottom: 16 }}>
            <strong>基本信息</strong>
            <div>名称: {record.name}</div>
            <div>型号: {record.model}</div>
            <div>序列号: {record.serialNumber}</div>
            <div>分类: {record.category}</div>
          </div>
          <div style={{ marginBottom: 16 }}>
            <strong>财务信息</strong>
            <div>购买日期: {record.purchaseDate}</div>
            <div>购买价格: ¥{record.purchasePrice}</div>
            <div>当前价值: ¥{record.currentValue}</div>
          </div>
          <div style={{ marginBottom: 16 }}>
            <strong>使用信息</strong>
            <div>状态: {statusTexts[record.status]}</div>
            <div>位置: {record.location}</div>
            {record.assignedTo && <div>使用人: {record.assignedTo}</div>}
          </div>
          <div style={{ marginBottom: 16 }}>
            <strong>维护信息</strong>
            <div>保修到期: {record.warrantyExpiry}</div>
            <div>最后维护: {record.maintenanceDate}</div>
          </div>
          {record.description && (
            <div>
              <strong>描述</strong>
              <div>{record.description}</div>
            </div>
          )}
        </div>
      )
    })
  }

  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确认删除这个资产记录吗？',
      onOk: () => {
        setAssets(prev => prev.filter(item => item.id !== id))
        message.success('删除成功')
      }
    })
  }

  const handleSubmit = async (values) => {
    setLoading(true)
    try {
      const formattedValues = {
        ...values,
        purchaseDate: values.purchaseDate.format('YYYY-MM-DD'),
        warrantyExpiry: values.warrantyExpiry.format('YYYY-MM-DD'),
        maintenanceDate: values.maintenanceDate?.format('YYYY-MM-DD') || ''
      }

      if (editingRecord) {
        setAssets(prev => 
          prev.map(item => 
            item.id === editingRecord.id ? { ...item, ...formattedValues } : item
          )
        )
        message.success('更新成功')
      } else {
        const newAsset = {
          id: Date.now(),
          ...formattedValues,
          image: ''
        }
        setAssets(prev => [...prev, newAsset])
        message.success('添加成功')
      }
      setModalVisible(false)
    } catch (error) {
      message.error('操作失败')
    } finally {
      setLoading(false)
    }
  }

  const uploadProps = {
    name: 'file',
    action: '/api/upload',
    listType: 'picture-card',
    maxCount: 1,
    onChange(info) {
      if (info.file.status === 'done') {
        message.success('图片上传成功')
      } else if (info.file.status === 'error') {
        message.error('图片上传失败')
      }
    },
  }

  return (
    <Layout>
      <div style={{ padding: '24px' }}>
        <Card 
          title="资产管理"
          extra={
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={handleAdd}
            >
              新增资产
            </Button>
          }
        >
          <Table
            columns={columns}
            dataSource={assets}
            rowKey="id"
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`
            }}
          />
        </Card>

        {/* 编辑/新增模态框 */}
        <Modal
          title={editingRecord ? '编辑资产' : '新增资产'}
          open={modalVisible}
          onOk={() => form.submit()}
          onCancel={() => setModalVisible(false)}
          confirmLoading={loading}
          width={800}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <Form.Item name="name" label="资产名称" rules={[{ required: true }]}>
                <Input placeholder="请输入资产名称" />
              </Form.Item>
              <Form.Item name="category" label="分类" rules={[{ required: true }]}>
                <Select placeholder="请选择分类">
                  {categoryOptions.map(cat => (
                    <Option key={cat} value={cat}>{cat}</Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item name="model" label="型号">
                <Input placeholder="请输入型号" />
              </Form.Item>
              <Form.Item name="serialNumber" label="序列号" rules={[{ required: true }]}>
                <Input placeholder="请输入序列号" />
              </Form.Item>
              <Form.Item name="purchaseDate" label="购买日期" rules={[{ required: true }]}>
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item name="purchasePrice" label="购买价格" rules={[{ required: true }]}>
                <Input type="number" placeholder="请输入购买价格" addonBefore="¥" />
              </Form.Item>
              <Form.Item name="currentValue" label="当前价值">
                <Input type="number" placeholder="请输入当前价值" addonBefore="¥" />
              </Form.Item>
              <Form.Item name="status" label="状态" rules={[{ required: true }]}>
                <Select placeholder="请选择状态">
                  <Option value="in_use">使用中</Option>
                  <Option value="available">可用</Option>
                  <Option value="maintenance">维护中</Option>
                  <Option value="retired">已报废</Option>
                  <Option value="lost">丢失</Option>
                </Select>
              </Form.Item>
              <Form.Item name="location" label="位置" rules={[{ required: true }]}>
                <Input placeholder="请输入位置" />
              </Form.Item>
              <Form.Item name="assignedTo" label="使用人">
                <Input placeholder="请输入使用人" />
              </Form.Item>
              <Form.Item name="warrantyExpiry" label="保修到期" rules={[{ required: true }]}>
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item name="maintenanceDate" label="最后维护日期">
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </div>
            <Form.Item name="description" label="描述">
              <TextArea rows={3} placeholder="请输入资产描述" />
            </Form.Item>
            <Form.Item name="image" label="资产图片">
              <Upload {...uploadProps}>
                <div>
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>上传图片</div>
                </div>
              </Upload>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </Layout>
  )
}